package com.hongkzh.www.user.service;

import com.aliyuncs.exceptions.ClientException;
import com.google.common.collect.Lists;
import com.hongkzh.www.adv.service.BaseService;
import com.hongkzh.www.adv.service.MediaService;
import com.hongkzh.www.conmon.*;
import com.jfinal.aop.Before;
import com.jfinal.kit.Kv;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jfinal.plugin.activerecord.tx.Tx;

import java.io.IOException;
import java.util.List;

/**
 * @author martins
 */
public class UserService extends BaseService {
    MediaService mediaService = new MediaService();

    public Record findDayIntegral(String id) {
        SqlPara sqlPara = Db.getSqlPara("user.findDayIntegral", id);
        Record record = Db.findFirst(sqlPara);
        if (record == null) {
            record = new Record();
            record.set("integral", 0);
        }
        if (StrKit.isBlank(record.getStr("integral"))) {
            record.set("integral", 0);
        }
        return record;

    }

    public Page<Record> followList(String id, int pageNumber) {
        SqlPara sqlPara = Db.getSqlPara("user.followList", id);
        Page<Record> records = Db.paginate(pageNumber, StaticPublic.LARGEPAGESIZE, sqlPara);

        for (Record r : records.getList()) {
            doFilePath(r);
        }
        return records;
    }

    public Page<Record> historyList(String id, int pageNumber) {
        SqlPara sqlPara = Db.getSqlPara("user.historyList", id);
        Page<Record> records = Db.paginate(pageNumber, StaticPublic.LARGEPAGESIZE, sqlPara);

        for (Record r : records.getList()) {
            doFilePath(r);
        }
        return records;
    }

    public void followDelete(String uid, String followUserId) {

        Db.update(Db.getSqlPara("user.followDelete", uid, followUserId));
    }

    @Before(Tx.class)
    public Record followAdd(String followUserId, String uid) {
        String fid = "";
        SqlPara sql = Db.getSqlPara("user.getfriend", followUserId, uid);
        List<Record> friends = Db.find(sql);
        //是好友
        if (friends != null && friends.size() > 0) {
            throw new BusinessException("已经是好友");
        }
        sql = Db.getSqlPara("user.getfollow", uid, followUserId);
        List<Record> follows = Db.find(sql);
        if (null != follows && follows.size() > 0) {
            throw new BusinessException("已经关注过了");
        }

        sql = Db.getSqlPara("user.getfollow", followUserId, uid);
        follows = Db.find(sql);
        //相互关注 变成好友
        if (null != follows && follows.size() > 0) {
            String id = IdGen.uuid();
            sql = Db.getSqlPara("user.friendAdd", id, followUserId, uid);
            Db.update(sql);
            Db.update(Db.getSqlPara("user.followDelete", followUserId, uid));
            Db.update(Db.getSqlPara("user.followDelete", uid, followUserId));
        } else {
            //未关注
            String sqlPara = Db.getSql("user.followAdd");
            fid = IdGen.uuid();
            Db.update(sqlPara, fid, uid, followUserId);
        }


        Record record = new Record();
        record.set("id", fid);
        return record;
    }

    public List<Record> historyAdd(String advId, String uid) {

        String sqlPara = Db.getSql("user.historyAdd");
        String id = IdGen.uuid();
        SqlPara advPara = Db.getSqlPara("adv.getAllAdvById", advId);
        Record r = Db.findFirst(advPara);
        if (r != null) {
            String type = r.getStr("type");
            Db.update(sqlPara, id, uid, r.getStr("imgSrc"), r.getStr("imgRank")
                    , advId, r.getStr("title"), type, r.getStr("coverImgSrc"));

            if ("1".equals(type)) {
                //自媒体
            } else if ("2".equals(type)) {
                //企业广告
            } else if ("3".equals(type)) {
                //城市广告
            } else if ("4".equals(type)) {
                //传统文化
            }
        }
        return null;
    }

    public Record getUserInfo(String loginUid, String uid) {
        SqlPara advPara = Db.getSqlPara("user.getUserInfo", loginUid, uid);
        Record r = Db.findFirst(advPara);
        doFilePath(r);

        r.set("followState", "0");
        if (StrKit.notBlank(r.getStr("followId"))) {
            r.set("followState", "1");
        }
        return r;
    }

    public Page<Record> getUserAdvList(String uid, int pageNumber, String sortId, String sortValue) {
        if ("create_date".equals(sortId)) {
            sortId = " a.create_date ";
        } else if ("rank".equals(sortId)) {
            sortId = " a.img_rank ";
        }
        Kv cond = Kv.by("uid", uid).set("order", " order by " + sortId + " " + sortValue);
        SqlPara sqlPara = Db.getSqlPara("user.getAllAdvByUserId", cond);
        Page<Record> records = Db.paginate(pageNumber, StaticPublic.PAGESIZE, sqlPara);

        for (Record r : records.getList()) {
            doFilePath(r);

        }
        return records;

    }

    public Page<Record> getAllAlbumByUserId(String uid, int pageNumber, String sortId, String sortValue) {

        Kv cond = Kv.by("uid", uid).set("order", " order by " + sortId + " " + sortValue);
        SqlPara sqlPara = Db.getSqlPara("user.getAllAlbumByUserId", cond);
        Page<Record> records = Db.paginate(pageNumber, StaticPublic.PAGESIZE, sqlPara);
        List<Record> details = Lists.newArrayList();
        for (Record r : records.getList()) {
            if (StrKit.notBlank(r.getStr("coverPhoto"))) {
                r.set("coverPhoto", PropKit.get("fileServer") + r.get("coverPhoto"));
            }
            details.clear();
            details = getAllAlbumContentByAlbumId(r.getStr("id"));
            r.set("details", details);
        }
        return records;
    }

    public List<Record> getAllAlbumContentByAlbumId(String albumId) {


        SqlPara sqlPara = Db.getSqlPara("user.getAllAlbumContentByAlbumId", albumId);
        List<Record> records = Db.find(sqlPara);

        for (Record r : records) {
            doFilePath(r);

        }
        return records;
    }

    public Page<Record> getAllProductByUserId(String uid, int pageNumber, String sortId, String sortValue) {
        Kv cond = Kv.by("uid", uid).set("order", " order by " + sortId + " " + sortValue);
        SqlPara sqlPara = Db.getSqlPara("user.getAllProductByUserId", cond);
        Page<Record> records = Db.paginate(pageNumber, StaticPublic.PAGESIZE, sqlPara);

        for (Record r : records.getList()) {
            doFilePath(r);

        }
        return records;
    }

    public void historyDelete(String id) {
        SqlPara sqlPara = Db.getSqlPara("user.historyDelete", id);
        Db.update(sqlPara);
    }

    @Before(Tx.class)
    public Record login(String mobile, String password, String registrationID) {

        SqlPara sqlPara = Db.getSqlPara("user.findByMobile", mobile);
        Record r = Db.findFirst(sqlPara);
        if (null == r) {
            return null;
        }

        //校验是否设置过密码
        if (StrKit.isBlank(r.getStr("password"))) {
            return null;
        }

        if (!PasswordUtils.validatePassword(password, r.getStr("password"))) {
            return null;
        }
        doLoginInfo(r, registrationID);
        return r;
    }

    @Before(Tx.class)
    public Record login(String mobile, String registrationID) {
        SqlPara sqlPara = Db.getSqlPara("user.findByMobile", mobile);
        Record r = Db.findFirst(sqlPara);
        r.remove("password");
        if (null != r) {
            doLoginInfo(r, registrationID);
        }
        return r;

    }

    @Before(Tx.class)
    public void addUserDeliveryAddress(String addressId, String loginUid, String consignee, String phone, String address, String isDefault, String provinceId, String cityId, String areaId) {
        if (StrKit.isBlank(addressId)) {
            String id = IdGen.uuid();
            if (isDefault.equals("1")) {
                Db.update(Db.getSqlPara("user.updateUserIsDefault", loginUid));
            }
            SqlPara sqlPara = Db.getSqlPara("user.addUserDeliveryAddress", id, loginUid, consignee, phone, address, isDefault, provinceId, cityId, areaId);
            Db.update(sqlPara);

        } else {
            if (isDefault.equals("1")) {
                Db.update(Db.getSqlPara("user.updateUserIsDefault", loginUid));
            }
            SqlPara sqlPara = Db.getSqlPara("user.updateUserDeliveryAddress", addressId, loginUid, consignee, phone, address, isDefault, provinceId, cityId, areaId);
            Db.update(sqlPara);
        }
    }

    public List<Record> getUserDeliveryAddressList(String loginUid) {

        SqlPara sqlPara = Db.getSqlPara("user.getUserDeliveryAddressList", loginUid);
        List<Record> recs = Db.find(sqlPara);
        return recs;

    }

    @Before(Tx.class)
    public void reduceIntegral(String loginUid, int boothMoney, String note) {
//        String key = "user-" + loginUid;
//        String requestId = IdGen.uuid();
//      RedisTool.tryGetDistributedLock(key, requestId, 3);
        Record userIntegralr = Db.findFirst(Db.getSqlPara("user.selectUserIntegral", loginUid));
        int userIntegral = userIntegralr.getInt("integral");
        if (userIntegral < boothMoney) {
            throw new BusinessException("乐币不够");
        }
        Db.update(Db.getSqlPara("user.reduceIntegral", boothMoney, loginUid));
        Db.update(Db.getSql("user.insertUserIntegral"), IdGen.uuid(), loginUid, boothMoney, 2, userIntegral - boothMoney, note);
//        RedisTool.releaseDistributedLock(key, requestId);
    }

    @Before(Tx.class)
    public void addIntegral(String loginUid, int integra, String note) {
        String key = "user-" + loginUid;
        String requestId = IdGen.uuid();
        RedisTool.tryGetDistributedLock(key, requestId, 3);
        Record userIntegralr = Db.findFirst(Db.getSqlPara("user.selectUserIntegral", loginUid));
        int userIntegral = userIntegralr.getInt("integral");
        Db.update(Db.getSqlPara("user.updateUserIntegral", integra, loginUid));
        Db.update(Db.getSql("user.insertUserIntegral"), IdGen.uuid(), loginUid, integra, 1, userIntegral + integra, note);
        RedisTool.releaseDistributedLock(key, requestId);
    }

    @Before(Tx.class)
    public void deleteUserDeliveryAddress(String addressId, String loginUid) throws Exception {
        List<Record> list = this.getUserDeliveryAddressList(loginUid);

        if (null != list && list.size() > 1) {
            Db.update(Db.getSqlPara("user.deleteUserDeliveryAddress", addressId, loginUid));
        } else {
            throw new Exception("不能删除");
        }
    }

    public Page<Record> myVideo(String categoryId, int pageNumber, String loginUid, String sourceId) {
        return mediaService.myVideo(categoryId, pageNumber, loginUid,sourceId);
    }

    /*public Page<Record> myVideoById(String categoryId, int pageNumber, String loginUid, String sourceId) {
        return mediaService.myVideoById(categoryId, pageNumber, loginUid, sourceId);
    }*/

    public List myVideoCategory(String loginUid) {
        return mediaService.myVideoCategory(loginUid);
    }

    public Page<Record> myTravels(int pageNumber, String loginUid) {
        return mediaService.myTravels(pageNumber, loginUid);
    }

    public Page<Record> myPosts(int pageNumber, String loginUid) {
        return mediaService.myPosts(pageNumber, loginUid);
    }

    public Page<Record> myRepliesPosts(int pageNumber, String loginUid) {
        return mediaService.myRepliesPosts(pageNumber, loginUid);
    }

    public Page<Record> myDelPosts(int pageNumber, String loginUid, String delType) {
        return mediaService.myDelPosts(pageNumber, loginUid, delType);
    }

    public Page<Record> myPraisePost(int pageNumber, String loginUid) {
        return mediaService.myPraisePost(pageNumber, loginUid);
    }

    public Page<Record> myForwardPost(int pageNumber, String loginUid) {
        return mediaService.myForwardPost(pageNumber, loginUid);
    }

    public Page<Record> myCollection(String categoryId, int pageNumber, String loginUid) {
        return mediaService.myCollection(categoryId, pageNumber, loginUid);
    }

    public List myCollectionCategory(String loginUid) {
        return mediaService.myCollectionCategory(loginUid);
    }


    public Page<Record> myPraise(String categoryId, int pageNumber, String loginUid) {
        return mediaService.myPraise(categoryId, pageNumber, loginUid);
    }

    public List myPraiseCategory(String loginUid) {
        return mediaService.myPraiseCategory(loginUid);
    }

    public Page myFans(String loginUid, int pageNumber) {
        Page<Record> records = Db.paginate(pageNumber, StaticPublic.PAGESIZE, Db.getSqlPara("user.myFans", loginUid));

        for (Record r : records.getList()
        ) {
            doImgPath(r);
        }
        return records;
    }

    public Page myFollows(String loginUid, int pageNumber) {
        Page<Record> list = Db.paginate(pageNumber, StaticPublic.LARGEPAGESIZE, Db.getSqlPara("user.myFollows", loginUid));
        for (Record r : list.getList()
        ) {
            doImgPath(r);
        }
        return list;
    }

    public Record myApply(String loginUid) {
        Record r = Db.findFirst(Db.getSqlPara("user.myApply", loginUid));
        doImgPath(r);
        doCache(r);
        return r;
    }


    public Page myFollowsEnterprise(String loginUid, int pageNumber) {
        Page<Record> list = Db.paginate(pageNumber, StaticPublic.LARGEPAGESIZE, Db.getSqlPara("user.myFollowsEnterprise", loginUid));
        for (Record r : list.getList()
        ) {
            doImgPath(r);
        }
        return list;
    }

    public Page<Record> myDelivery(String loginUid, int pageNumber, String state) {
        Kv cond = Kv.by("user_id", loginUid);
        cond.set("state", state);
        SqlPara sqlPara = Db.getSqlPara("user.myDelivery", cond);
        Page<Record> records = Db.paginate(pageNumber, StaticPublic.PAGESIZE, sqlPara);
        List<Record> logs;
        for (Record r : records.getList()) {
            doImgPath(r);
            doCache(r);
            logs = Db.find(Db.getSqlPara("user.deliveryLog", r.getStr("deliveryId")));
            r.set("logs", logs);
        }
        return records;

    }

    public Record myResume(String loginUid) {
        Record r = Db.findFirst(Db.getSqlPara("recruit.getUserInfo", loginUid));
        doCache(r);
        doImgPath(r);

        SqlPara sqlPara = Db.getSqlPara("recruit.getUserEducational", r.get("resumeId"), loginUid);
        List<Record> list = Db.find(sqlPara);
        for (Record s : list
        ) {
            doCache(s);
        }
        r.set("educationals", list);

        sqlPara = Db.getSqlPara("recruit.getUserExperience", r.get("resumeId"), loginUid);
        List<Record> list2 = Db.find(sqlPara);
        for (Record r2 : list2
        ) {
            doCache(r2);
        }
        r.set("experiences", list2);
        sqlPara = Db.getSqlPara("recruit.getUserPhotography", loginUid);
        List<Record> list3 = Db.find(sqlPara);
        for (Record r2 : list3
        ) {
            doImgPath(r2);
        }
        r.set("imgs", list3);

        return r;
    }

    public Record myRecruit(String loginUid) {

        Record r = Db.findFirst(Db.getSqlPara("recruit.getUserEnterprise", loginUid));
        String enterpriseId = r.getStr("enterpriseId");
        List<Record> r2 = Db.find(Db.getSqlPara("recruit.getRecruitByEnterpriseId", enterpriseId));
        r.set("recruitCount", r2.size());
        r.set("recruits", r2);
        Record r3 = Db.findFirst(Db.getSqlPara("recruit.getEnterpriseCollectionCount", enterpriseId));
        r.set("collectionCount", r3.get("collectionCount"));
        Record r4 = Db.findFirst(Db.getSqlPara("recruit.getDeliveryCount", enterpriseId));
        r.set("deliveryCount", r4.get("deliveryCount"));

        return r;
    }

    public Page<Record> myRecruitRecommend(String loginUid, int pageNumber, String title) {
        Record r = Db.findFirst(Db.getSqlPara("recruit.getUserEnterprise", loginUid));
        String enterpriseId = r.getStr("enterpriseId");

        Kv cond = Kv.by("enterpriseId", enterpriseId);
        if (StrKit.notBlank(title)) {
            cond.set("title", title);
        }
        SqlPara sqlPara = Db.getSqlPara("user.myRecruitRecommend", cond);
        Page<Record> records = Db.paginate(pageNumber, StaticPublic.PAGESIZE, sqlPara);
        List<Record> rs = Lists.newArrayList();
        for (Record r2 : records.getList()
        ) {
            r2 = Db.findFirst(Db.getSqlPara("user.getResumeInfo", r2.getStr("resumeId")));
            r2.set("time", DateUtil.CalculateTime(r2.getStr("updateDate")));
            doCache(r2);
            doImgPath(r2);
            rs.add(r2);
        }

        return new Page<Record>(rs, records.getPageNumber(), records.getPageSize(), records.getTotalPage(), records.getTotalRow());
    }

    public Page<Record> getUserResumeList(String workingLifeId, int pageNumber, String education, String age, String title, String areaId) {

        Kv cond = new Kv();
        if (StrKit.notBlank(workingLifeId)) {
            cond.set("workingLifeId", workingLifeId);
        }
        if (StrKit.notBlank(education)) {
            cond.set("education", education);
        }
        if (StrKit.notBlank(title)) {
            cond.set("title", title);
        }
        if (StrKit.notBlank(areaId)) {
            cond.set("areaId", areaId);
        }
        if (StrKit.notBlank(age)) {
            String ageName = RedisTool.hgetDict("hk_recruit_age:" + age);
            if (StrKit.notBlank(ageName)) {
                String[] ages = ageName.split("岁")[0].split("-");
                cond.set("age1", ages[0]);
                cond.set("age2", ages[1]);
            }
        }
        SqlPara sqlPara = Db.getSqlPara("user.getUserResumeList", cond);
        Page<Record> records = Db.paginate(pageNumber, StaticPublic.PAGESIZE, sqlPara);
        List<Record> rs = Lists.newArrayList();
        for (Record r2 : records.getList()
        ) {
            r2 = Db.findFirst(Db.getSqlPara("user.getResumeInfo", r2.getStr("resumeId")));
            r2.set("time", DateUtil.CalculateTime(r2.getStr("updateDate")));
            doCache(r2);
            doImgPath(r2);
            rs.add(r2);
        }

        return new Page<Record>(rs, records.getPageNumber(), records.getPageSize(), records.getTotalPage(), records.getTotalRow());

    }

    public List<Record> getRecruitByUserId(String loginUid) {
        Record r = Db.findFirst(Db.getSqlPara("recruit.getUserEnterprise", loginUid));
        String enterpriseId = r.getStr("enterpriseId");
        List<Record> list = Db.find(Db.getSqlPara("user.getRecruitByUserId", enterpriseId));
        for (Record r1 : list
        ) {
            doCache(r1);
            r1.set("updateTime", DateUtil.CalculateTime(r1.getStr("updateDate")));
        }
        return list;
    }

    public List<Record> getRecruitDownByUserId(String loginUid) {
        Record r = Db.findFirst(Db.getSqlPara("recruit.getUserEnterprise", loginUid));
        String enterpriseId = r.getStr("enterpriseId");
        List<Record> list = Db.find(Db.getSqlPara("user.getRecruitDownByUserId", enterpriseId));
        for (Record r1 : list
        ) {
            doCache(r1);
        }
        return list;
    }

    public void updateRecruitById(String loginUid, String recruitId) {
        Record r = Db.findFirst(Db.getSqlPara("recruit.getUserEnterprise", loginUid));
        String enterpriseId = r.getStr("enterpriseId");
        Db.update(Db.getSqlPara("user.updateRecruitById", enterpriseId, recruitId));
    }

    public void deleteRecruitById(String loginUid, String recruitId) {
        Record r = Db.findFirst(Db.getSqlPara("recruit.getUserEnterprise", loginUid));
        String enterpriseId = r.getStr("enterpriseId");
        Db.update(Db.getSqlPara("user.deleteRecruitById", enterpriseId, recruitId));


    }

    public void downRecruitById(String loginUid, String recruitId) {
        Record r = Db.findFirst(Db.getSqlPara("recruit.getUserEnterprise", loginUid));
        String enterpriseId = r.getStr("enterpriseId");
        Db.update(Db.getSqlPara("user.downRecruitById", enterpriseId, recruitId));


    }

    public void upRecruitById(String loginUid, String recruitId) {
        Record r = Db.findFirst(Db.getSqlPara("recruit.getUserEnterprise", loginUid));
        String enterpriseId = r.getStr("enterpriseId");
        Db.update(Db.getSqlPara("user.upRecruitById", enterpriseId, recruitId));

    }

    public Page<Record> myCandidate(String loginUid, int pageNumber, String recruitId, String state) {
        Record r = Db.findFirst(Db.getSqlPara("recruit.getUserEnterprise", loginUid));
        String enterpriseId = r.getStr("enterpriseId");

        Kv cond = Kv.by("enterpriseId", enterpriseId);
        if (StrKit.notBlank(recruitId)) {
            cond.set("recruitId", recruitId);
        }
        if (StrKit.notBlank(state)) {
            cond.set("state", state);
        }
        SqlPara sqlPara = Db.getSqlPara("user.myCandidate", cond);
        Page<Record> records = Db.paginate(pageNumber, StaticPublic.PAGESIZE, sqlPara);
        List<Record> rs = Lists.newArrayList();
        Record r3;
        for (Record r2 : records.getList()
        ) {
            r3 = Db.findFirst(Db.getSqlPara("user.getResumeInfo", r2.getStr("resumeId")));
            r3.set("time", DateUtil.CalculateTime(r3.getStr("updateDate")));
            doCache(r3);
            r3.set("recruitId", r2.get("recruitId"));
            r3.set("recruitName", r2.get("recruitName"));
            doImgPath(r3);
            rs.add(r3);
        }

        return new Page<Record>(rs, records.getPageNumber(), records.getPageSize(), records.getTotalPage(), records.getTotalRow());
    }

    public Record myResumePreview(String loginUid, String recruitId, String resumeId) {
        Record r = Db.findFirst(Db.getSqlPara("recruit.getUserEnterprise", loginUid));
        String enterpriseId = "";
        if (r != null) {
            enterpriseId = r.getStr("enterpriseId");
        }
        r = Db.findFirst(Db.getSqlPara("user.getResumeUserInfo", resumeId));
        doCache(r);
        doImgPath(r);

        SqlPara sqlPara = Db.getSqlPara("recruit.getUserEducational", resumeId);
        List<Record> list = Db.find(sqlPara);
        for (Record s : list
        ) {
            doCache(s);
        }
        r.set("educationals", list);
        r.set("corporateName", "");
        sqlPara = Db.getSqlPara("recruit.getUserExperience", r.getStr("resumeId"));
        List<Record> list2 = Db.find(sqlPara);
        for (Record r2 : list2
        ) {
            doCache(r2);
        }
        if (list2 != null && list2.size() > 0) {
            r.set("corporateName", list2.get(0).getStr("corporateName"));
        }
        r.set("experiences", list2);
        sqlPara = Db.getSqlPara("recruit.getUserPhotography", r.getStr("id"));
        List<Record> list3 = Db.find(sqlPara);
        for (Record r2 : list3
        ) {
            doImgPath(r2);
        }
        r.set("imgs", list3);
        r.set("recruitName", "");
        r.set("recruitState", "1");
        if (StrKit.notBlank(recruitId)) {
            sqlPara = Db.getSqlPara("user.getRecruitInfo", recruitId, r.getStr("id"));
            Record r2 = Db.findFirst(sqlPara);
            r.set("recruitName", r2.get("title"));
            r.set("recruitState", r2.get("recruitState"));
        }
        r.set("collectionState", "0");
        if (StrKit.notBlank(enterpriseId)) {
            sqlPara = Db.getSqlPara("user.getEnterpriseCollection", enterpriseId, r.getStr("id"));
            Record r2 = Db.findFirst(sqlPara);
            if (r2 != null && StrKit.notBlank(r2.getStr("collectionId"))) {
                r.set("collectionState", "1");
            }
        }
        r.set("updateDate", DateUtil.CalculateTime(r.getStr("updateDate")));


        return r;
    }

    @Before(Tx.class)
    public void viewResume(String loginUid, String recruitId, String resumeId) {
        Record r = Db.findFirst(Db.getSqlPara("user.deliveryId", resumeId, recruitId));
        savedeliveryLog("你的简历被查看", r.getStr("id"));
        Db.update(Db.getSqlPara("user.updateRecruitDeliveryState", resumeId, recruitId, "2"));
    }

    @Before(Tx.class)
    public void notGoodResume(String loginUid, String recruitId, String resumeId) {
        Record r = Db.findFirst(Db.getSqlPara("user.deliveryId", resumeId, recruitId));
        savedeliveryLog("你的简历不符", r.getStr("id"));
        Db.update(Db.getSqlPara("user.updateRecruitDeliveryState", resumeId, recruitId, "3"));
    }

    private void savedeliveryLog(String content, String did) {
        Db.update(Db.getSqlPara("user.savedeliveryLog", IdGen.uuid(), content, did));
    }

    public void resumeCollection(String loginUid, String resumeId, String state) {
        Record r = Db.findFirst(Db.getSqlPara("recruit.getUserEnterprise", loginUid));
        String enterpriseId = r.getStr("enterpriseId");
        if (state.equals("1")) {
            Record r2 = Db.findFirst(Db.getSqlPara("user.getResumeUserInfo", resumeId));
            Db.update(Db.getSqlPara("user.enterpriseCollection", IdGen.uuid(), resumeId,
                    r2.getStr("id"), enterpriseId, "1"));
        } else {
            Record r2 = Db.findFirst(Db.getSqlPara("user.getResumeUserInfo", resumeId));
            Db.update(Db.getSqlPara("user.enterpriseremoveCollection", resumeId,
                    r2.getStr("id"), enterpriseId, "1"));
        }
    }

    public Record editResume(String loginUid) {
        Record record = Db.findFirst(Db.getSqlPara("user.selectUserResume", loginUid));
        if (null != record) {
            doImgPath(record);
            List<Record> imgs = Db.find(Db.getSqlPara("user.selectUserResumeImg", loginUid));
            for (Record r : imgs
            ) {
                doImgPath(r);
            }
            record.set("imgs", imgs);
            record.set("complete", "100%");
        }
        return record;
    }

    public Record editRecruitment(String loginUid) {
        Record record = Db.findFirst(Db.getSqlPara("user.editRecruitment", loginUid));
        doImgPath(record);
        return record;
    }

    public void refreshResume(String loginUid, String resumeId) {
        Db.update(Db.getSqlPara("user.refreshResume", resumeId, loginUid));
    }

    public Page<Record> myTalentCollection(String loginUid, int pageNumber) {
        Record r = Db.findFirst(Db.getSqlPara("recruit.getUserEnterprise", loginUid));
        String enterpriseId = r.getStr("enterpriseId");
        Kv cond = Kv.by("enterpriseId", enterpriseId);
        SqlPara sqlPara = Db.getSqlPara("user.myTalentCollection", cond);
        Page<Record> records = Db.paginate(pageNumber, StaticPublic.PAGESIZE, sqlPara);
        List<Record> rs = Lists.newArrayList();
        for (Record r2 : records.getList()
        ) {
            r2 = Db.findFirst(Db.getSqlPara("user.getResumeInfo", r2.getStr("resumeId")));
            r2.set("time", DateUtil.CalculateTime(r2.getStr("updateDate")));
            doCache(r2);
            doImgPath(r2);
            rs.add(r2);
        }

        return new Page<Record>(rs, records.getPageNumber(), records.getPageSize(), records.getTotalPage(), records.getTotalRow());
    }

    public Page recommendFans(String loginUid, int pageNumber, String content) {
        Kv cond = Kv.by("loginUid", loginUid);
        cond.set("content", content);
        Page<Record> list = Db.paginate(pageNumber, StaticPublic.PAGESIZE, Db.getSqlPara("user.recommendFans", cond));
        for (Record r : list.getList()
        ) {
            doImgPath(r);
        }
        return list;
    }

    public List mobile(String loginUid, String mobile) {
        List<Record> list = Lists.newArrayList();
        String mobiles[] = mobile.split(",");
        String uid;
        Record r1, r2;

        for (String s : mobiles
        ) {
            r1 = Db.findFirst(Db.getSqlPara("user.getUserInfoByMobile", s));
            if (null == r1) {
                r1 = new Record();
                r1.set("mobile", s);
                r1.set("state", "1");
            } else {
                uid = r1.getStr("uid");
                r2 = Db.findFirst(Db.getSqlPara("user.getfriend", loginUid, uid));
                if (null != r2) {
                    r1.set("mobile", s);
                    r1.set("state", "2");
                } else {
                    r2 = Db.findFirst(Db.getSqlPara("user.getfollow", loginUid, uid));
                    if (null != r2) {
                        r1.set("mobile", s);
                        r1.set("state", "3");
                    } else {

                        r1.set("mobile", s);
                        r1.set("state", "4");
                    }
                }
            }
            list.add(r1);
        }
        for (Record r : list
        ) {
            doImgPath(r);
        }
        return list;
    }


    @Before(Tx.class)
    public void addUserReturnAddress(String addressId, String loginUid, String consignee, String phone, String address, String isDefault, String provinceId, String cityId, String areaId) {
        if (StrKit.isBlank(addressId)) {
            String id = IdGen.uuid();
            SqlPara sqlPara = Db.getSqlPara("user.addUserReturnAddress", id, loginUid, consignee, phone, address, isDefault, provinceId, cityId, areaId);
            Db.update(sqlPara);
        } else {
            SqlPara sqlPara = Db.getSqlPara("user.updateUserReturnAddress", addressId, loginUid, consignee, phone, address, isDefault, provinceId, cityId, areaId);
            Db.update(sqlPara);
        }
    }

    public List<Record> getUserReturnAddressList(String loginUid) {
        SqlPara sqlPara = Db.getSqlPara("user.getUserReturnAddressList", loginUid);
        List<Record> recs = Db.find(sqlPara);
        return recs;

    }

    public void deleteUserReturnAddress(String addressId, String loginUid) throws Exception {
        List<Record> list = this.getUserReturnAddressList(loginUid);

        if (null != list && list.size() > 1) {
            Db.update(Db.getSqlPara("user.deleteUserReturnAddress", addressId, loginUid));
        } else {
            throw new Exception("不能删除");
        }
    }

    private String getCode() {
        String code = BigNumberFormat.getAppCode();
        String redisCode = (String) RedisTool.getObject(code);
        if (StrKit.notBlank(redisCode)) {
            code = getCode();
        }
        return code;
    }

    public Record presendMessage(String registrationID) {
        String key = String.format(StaticPublic.PRESHORTMESSAGE, registrationID);
        String code = (String) RedisTool.getObject(key);
        if (StrKit.isBlank(code)) {
            code = getCode();
            RedisTool.setexObject(key, StaticPublic.SHORTMESSAGE, code);
        }
        Record record = new Record();
        record.set("verificationCode", code);
        return record;
    }

    public Record updateregistermessage(String mobile, String registrationID, String verificationCode, String ymobile) {
        SqlPara sqlPara = Db.getSqlPara("user.findByMobile", ymobile);
        Record r = Db.findFirst(sqlPara);
        if (null == r) {
            throw new BusinessException("用户不存在");
        }
        return sendmessage(mobile, registrationID, verificationCode, "4");
    }

    /**
     * @param mobile
     * @param registrationID
     * @param verificationCode
     * @param type             1注册 2登录
     * @return
     * @throws BusinessException
     */
    public Record sendmessage(String mobile, String registrationID, String verificationCode, String type) throws BusinessException {
        Record record = new Record();
        String key = String.format(StaticPublic.PRESHORTMESSAGE, registrationID);
        String code = (String) RedisTool.getObject(key);
        if (StrKit.isBlank(mobile)) {
            record.set("verificationCode", "");
            record.set("data", "手机错误");
            throw new BusinessException("手机错误");
        }
        if (!BigNumberFormat.isPhone(mobile)) {
            record.set("verificationCode", "");
            record.set("data", "手机错误");
            throw new BusinessException("手机错误");
        }

        if (StrKit.isBlank(code)) {
            throw new BusinessException("验证码超时");
        }
        if (!verificationCode.equals(code)) {
            throw new BusinessException("验证码错误");
        }
        //注册
        if ("1".equals(type)) {
            SqlPara sqlPara = Db.getSqlPara("user.findByMobile", mobile);
            Record r = Db.findFirst(sqlPara);
            if (null != r) {
                throw new BusinessException("用户已存在");
            }
            RedisTool.del(key);
            code = getCode();
            try {
                SendMessage.sendRegisterMessageCode(mobile, code);
            } catch (ClientException e) {
                throw new BusinessException("短信发送失败");
            }
        }
        //登录
        else if ("2".equals(type)) {
            SqlPara sqlPara = Db.getSqlPara("user.findByMobile", mobile);
            Record r = Db.findFirst(sqlPara);
            if (null == r) {
                throw new BusinessException("用户不存在");
            }
            RedisTool.del(key);
            code = getCode();
            try {
                SendMessage.sendLoginMessageCode(mobile, code);
            } catch (ClientException e) {
                throw new BusinessException("短信发送失败");
            }
        }
        //忘记密码
        else if ("3".equals(type)) {
            SqlPara sqlPara = Db.getSqlPara("user.findByMobile", mobile);
            Record r = Db.findFirst(sqlPara);
            if (null == r) {
                throw new BusinessException("用户不存在");
            }
            RedisTool.del(key);
            code = getCode();
            try {
                SendMessage.sendForgetMessageCode(mobile, code);
            } catch (ClientException e) {
                throw new BusinessException("短信发送失败");
            }
        }
        //修改手机号
        else if ("4".equals(type)) {

            RedisTool.del(key);
            code = getCode();
            try {
                SendMessage.sendUpdateMessageCode(mobile, code);
            } catch (ClientException e) {
                throw new BusinessException("短信发送失败");
            }
        }
        RedisTool.setexObject(key, StaticPublic.SHORTMESSAGE, code);
        record.set("verificationCode", code);

        return record;
    }

    @Before(Tx.class)
    public Record register(String mobile, String verificationCode, String registrationID) throws BusinessException {

        SqlPara sqlPara = Db.getSqlPara("user.findByMobile", mobile);
        Record r = Db.findFirst(sqlPara);
        if (null != r) {
            throw new BusinessException("用户已存在");
        }

        String key = String.format(StaticPublic.PRESHORTMESSAGE, registrationID);
        String code = (String) RedisTool.getObject(key);
        if (StrKit.isBlank(code)) {
            throw new BusinessException("验证码超时");
        }
        if (!verificationCode.equals(code)) {
            throw new BusinessException("验证码错误");
        }
        RedisTool.del(key);
        String id = IdGen.uuid();
        String str = "";
        for (int i = 0; i < 5; i++) {
            str = str + (char) (Math.random() * 26 + 'A');
        }
        Db.update(Db.getSqlPara("user.register", id, mobile, str));
        Record r1 = login(mobile, registrationID);
        r1.set("isFirst", 1);
        registerOK(id);
        return r1;
    }

    public Record loginByCode(String mobile, String verificationCode, String registrationID) throws BusinessException {
        String key = String.format(StaticPublic.PRESHORTMESSAGE, registrationID);
        String code = (String) RedisTool.getObject(key);
        if (StrKit.isBlank(code)) {
            throw new BusinessException("验证码超时");
        }
        if (!verificationCode.equals(code)) {
            throw new BusinessException("验证码错误");
        }

        RedisTool.del(key);

        return this.login(mobile, registrationID);
    }

    public Record myWallet(String loginUid) {
        Record record = Db.findFirst(Db.getSqlPara("user.myWallet", loginUid));

        return record;
    }

    public Page myWalletLog(String loginUid, int pageNumber) {
        Page page = Db.paginate(pageNumber, StaticPublic.PAGESIZE, Db.getSqlPara("user.myWalletLog", loginUid));

        return page;
    }

    public Record myWalletLogDetails(String loginUid, String logId) {
        return Db.findFirst(Db.getSqlPara("user.myWalletLogDetails", logId));
    }

    @Before(Tx.class)
    public Record setForgetCode(String mobile, String password, String registrationID) {
        password = PasswordUtils.entryptPassword(password);
        Db.update(Db.getSqlPara("user.setForgetCode", mobile, password));
        return this.login(mobile, registrationID);
    }

    @Before(Tx.class)
    public Record weixinlogin(String code, String registrationID) throws IOException {
        WeiXinData wd = WeiXin.weixinlogin(code);

        return this.openidlogin(wd, registrationID);
    }

    @Before(Tx.class)
    public Record weixinbind(String code, String loginUid) {
        Record record = new Record();
        WeiXinData wd = null;
        WeiXinUserInfo wu = null;
        try {
            wd = WeiXin.weixinlogin(code);
            wu = WeiXin.weixingetuserinfo(wd.getAccess_token(), wd.getOpenid());
        } catch (IOException e) {
            record.set("code", 1);
            record.set("msg", "绑定失败");
            return record;
        }
        SqlPara sqlPara = Db.getSqlPara("user.findByOpenid", wd.getOpenid());
        Record r = Db.findFirst(sqlPara);
        record.set("code", 0);
        if (null != r) {
            record.set("code", 1);
            record.set("msg", "此微信已绑定");
            return record;
        }

        Db.update(Db.getSqlPara("user.saveuserlogin", IdGen.uuid(), loginUid, wd.getOpenid(), "1", wu.getNickname()));

        return record;
    }

    @Before(Tx.class)
    public Record openidlogin(WeiXinData wd, String registrationID) throws IOException {
        SqlPara sqlPara = Db.getSqlPara("user.findByOpenid", wd.getOpenid());
        Record r = Db.findFirst(sqlPara);
        if (null != r) {
            doLoginInfo(r, registrationID);
        } else {
            WeiXinUserInfo wu = WeiXin.weixingetuserinfo(wd.getAccess_token(), wd.getOpenid());
            String id = IdGen.uuid();
            Db.update(Db.getSqlPara("user.registerWx", id, wu.getSex(), wu.getNickname(), wu.getHeadimgurl()));
            Db.update(Db.getSqlPara("user.saveuserlogin", IdGen.uuid(), id, wd.getOpenid(), "1", wu.getNickname()));
            Record r1 = openidlogin(wd, registrationID);
            r1.set("isFirst", 1);
            registerOK(id);
            return r1;
        }
        return r;

    }

    private void doLoginInfo(Record r, String registrationID) {
        doFilePath(r);
        if (StrKit.isBlank(r.get("token"))) {
            try {
                RongCloudTool.registerUser(r);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (StrKit.notBlank(registrationID)) {
            Db.update(Db.getSqlPara("user.updateUserRegistrationID", r.get("id"), registrationID));
        }
        // registrationID
        String key = r.get("id");
        r.set("chatId", key);
        String tokenId = JwtUtil.sign(key, 24 * 60 * 60 * 15);
        r.set("loginUid", tokenId);
        //缓存用户token
        RedisTool.setexObject(tokenId, StaticPublic.USERTOKENTIME, key);
        //缓存用户信息
        RedisTool.setexObject(key, StaticPublic.USERTOKENTIME, r);
        r.remove("uid");
        r.remove("id");
        r.remove("password");
    }

    @Before(Tx.class)
    public Record qqlogin(String headImg, String openid, String name, String registrationID) {
        SqlPara sqlPara = Db.getSqlPara("user.findByOpenid", openid);
        Record r = Db.findFirst(sqlPara);
        if (null != r) {
            doLoginInfo(r, registrationID);
        } else {
            String id = IdGen.uuid();
            Db.update(Db.getSqlPara("user.registerWx", id, 1, name, headImg));
            Db.update(Db.getSqlPara("user.saveuserlogin", IdGen.uuid(), id, openid, "2", name));
            Record r1 = qqlogin(headImg, openid, name, registrationID);
            r1.set("isFirst", 1);
            registerOK(id);
            return r1;
        }
        return r;
    }

    private void registerOK(String uid) {
        addIntegral(uid, 50, "注册");
        Db.update(Db.getSqlPara("user.saveValidQualificationCoupon", IdGen.uuid(), uid, DateUtil.addDate(0), DateUtil.addDate(7)));
    }

    public Record myIncome(String loginUid, int day) {
        Record record = new Record();
        List<Record> days = Lists.newArrayList();
        int count = 0;
        for (int i = day; i > 0; i--) {
            Record record2 = Db.findFirst(Db.getSqlPara("user.myIncome", loginUid, DateUtil.reduceDateYYYYMMDD(i)));
            days.add(record2);
            count += record2.getInt("integral");
        }
        record.set("days", days);
        record.set("countIntegral", count);
        record.set("transactionIntegral", Db.findFirst(Db.getSqlPara("user.gettransactionIntegral", loginUid)).getInt("transactionIntegral"));
        record.set("settlementIntegral", Db.findFirst(Db.getSqlPara("user.getsettlementIntegral", loginUid)).getInt("settlementIntegral"));
        //transaction
        //settlement
        return record;
    }

    public Record webloginByCode(String mobile, String verificationCode, String registrationID) {
        String key = String.format(StaticPublic.PRESHORTMESSAGE, registrationID);
        String code = (String) RedisTool.getObject(key);
        if (StrKit.isBlank(code)) {
            throw new BusinessException("验证码超时");
        }
        if (!verificationCode.equals(code)) {
            throw new BusinessException("验证码错误");
        }
        RedisTool.del(key);

        return this.login(mobile, null);
    }

    public Record weblogin(String mobile, String password, String registrationID) {
        SqlPara sqlPara = Db.getSqlPara("user.findByMobile", mobile);
        Record r = Db.findFirst(sqlPara);
        if (null == r) {
            return null;
        }
        if (!PasswordUtils.validatePassword(password, r.getStr("password"))) {
            return null;
        }
        r.remove("password");
        doLoginInfo(r, null);
        return r;
    }

    @Before(Tx.class)
    public void setFirstInfo(String loginUid, String birthday, String sex) {
        Db.update(Db.getSqlPara("user.setFirstInfo", loginUid, birthday, sex));
    }

    @Before(Tx.class)
    public void setSecondInfo(String loginUid, String headImg, String name) {
        Db.update(Db.getSqlPara("user.setSecondInfo", loginUid, headImg, name));
    }

    public Record getUserIntegral(String loginUid) {
        return Db.findFirst(Db.getSqlPara("user.getUserIntegral", loginUid));
    }

    public Record getUserLabel(String loginUid) {
        Record record = new Record();
        List<Record> userlabels = Db.find(Db.getSqlPara("user.getUserLabel", loginUid));
        record.set("userlabels", userlabels);
        List<Record> systemlabels = Db.find(Db.getSqlPara("user.systemlabels", 0));
        for (Record r : systemlabels
        ) {
            r.set("childrenlabels", Db.find(Db.getSqlPara("user.systemlabels", r.getStr("id"))));
        }
        record.set("systemlabels", systemlabels);

        return record;
    }

    @Before(Tx.class)
    public void saveUserLabel(String loginUid, String labels) {
        Db.update(Db.getSqlPara("user.deleteUserlabel", loginUid));
        String[] ls = labels.split(",");
        for (String s : ls
        ) {
            Db.update(Db.getSqlPara("user.saveUserLabel", IdGen.uuid(), loginUid, s));
        }
    }

    public Record myData(String loginUid) {
        Record record = new Record();
        record.set("dayIncome", 0);
        record.set("currentLevelNum", 0);//当前等级数
        record.set("enoughLevelNum", 0);//满足等级数
        record.set("collections", Db.findFirst(Db.getSqlPara("user.getUserCollections", loginUid)).getInt("count"));
        record.set("praises", Db.findFirst(Db.getSqlPara("user.getUserPraise", loginUid)).getInt("count"));
        record.set("follows", Db.findFirst(Db.getSqlPara("user.getUserFollows", loginUid)).getInt("count"));
        record.set("fans", Db.findFirst(Db.getSqlPara("user.getUserFans", loginUid)).getInt("count"));
        record.set("carts", Db.findFirst(Db.getSqlPara("user.getUserCarts", loginUid)).getInt("count"));
        record.set("orders", Db.findFirst(Db.getSqlPara("user.getUserOrders", loginUid)).getInt("count"));
        record.set("afterService", Db.findFirst(Db.getSqlPara("user.getUserAfterService", loginUid)).getInt("count"));
        record.set("sells", Db.findFirst(Db.getSqlPara("user.getUserSells", loginUid)).getInt("count"));
        record.set("jobs", Db.findFirst(Db.getSqlPara("user.getUserAfterService", loginUid)).getInt("count"));
        record.set("task", 0);
        record.set("answer", 0);

        return record;
    }


    @Before(Tx.class)
    public Record qqbind(String loginUid, String code, String name) {
        Record record = new Record();
        SqlPara sqlPara = Db.getSqlPara("user.findByOpenid", code);
        Record r = Db.findFirst(sqlPara);
        record.set("code", 0);
        if (null != r) {
            record.set("code", 1);
            record.set("msg", "此QQ已绑定");
        }
        Db.update(Db.getSqlPara("user.saveuserlogin", IdGen.uuid(), loginUid, code, "2", name));

        return record;
    }

    @Before(Tx.class)
    public void updateMobile(String mobile, String verificationCode, String registrationID, String ymobile) {

        SqlPara sqlPara = Db.getSqlPara("user.findByMobile", ymobile);
        Record r = Db.findFirst(sqlPara);
        if (null == r) {
            throw new BusinessException("用户不存在");
        }
        String key = String.format(StaticPublic.PRESHORTMESSAGE, registrationID);
        String code = (String) RedisTool.getObject(key);
        if (StrKit.isBlank(code)) {
            throw new BusinessException("验证码超时");
        }
        if (!verificationCode.equals(code)) {
            throw new BusinessException("验证码错误");
        }
        RedisTool.del(key);
        Db.update(Db.getSqlPara("user.updateMobile", mobile, r.get("id")));
    }

    public Record getUserInfoById(String loginUid) {
        Record record = Db.findFirst(Db.getSqlPara("user.getUserMobileById", loginUid));
        if (StrKit.notBlank(record.getStr("password"))) {
            record.set("password", "1");
        } else {
            record.set("password", "0");
        }
        List<Record> list = Db.find(Db.getSqlPara("user.getUserLoginById", loginUid));
        record.set("weixin", "");
        record.set("qq", "");
        for (Record r : list
        ) {
            if (r.getInt("type") == 1) {
                record.set("weixin", r.getStr("name"));
            } else if (r.getInt("type") == 2) {
                record.set("qq", r.getStr("name"));
            }
        }

        return record;

    }

    @Before(Tx.class)
    public void setUserMobile(String loginUid, String mobile) {
        Db.update(Db.getSqlPara("user.updateMobile", mobile, loginUid));
    }

    public Page<Record> myCoupon(String loginUid, int pageNumber, String state) {
        Page<Record> list = Db.paginate(pageNumber, StaticPublic.PAGESIZE, Db.getSqlPara("shop.myCoupon", loginUid, state));
        for (Record r : list.getList()
        ) {
            doImgPath(r);
        }
        return list;
    }

    @Before(Tx.class)
    public void deleteCoupon(String loginUid, String couponId) {
        Db.update(Db.getSqlPara("user.deleteCoupon", loginUid, couponId));
    }

    public Record myQualificationCoupon(String loginUid, String state) {
        return Db.findFirst(Db.getSqlPara("user.myQualificationCoupon", loginUid, state));
    }

    @Before(Tx.class)
    public void applyShop(String loginUid, String provinceId, String cityId, String contacts,
                          String name, String telephone) {
        Kv cond = new Kv();
        cond.set("loginUid", loginUid);
        cond.set("provinceId", provinceId);
        cond.set("cityId", cityId);
        cond.set("contacts", contacts);
        cond.set("name", name);
        cond.set("telephone", telephone);
        cond.set("id", IdGen.uuid());
        Record r = isShop(loginUid);
        if (null == r || StrKit.isBlank(r.get("shopId"))) {
            Db.update(Db.getSqlPara("shop.applyShop", cond));
        }
    }

    public Record isShop(String loginUid) {
        Record r = Db.findFirst(Db.getSqlPara("shop.getUserShopByUid", loginUid));
        if (r == null) {
            r = new Record();
            r.set("shopid", "");
        }
        return r;
    }

    public Record isRealName(String loginUid) {
        Record r = Db.findFirst(Db.getSqlPara("shop.isRealName", loginUid));
        if (r == null) {
            r = new Record();
            r.set("state", "0");
        }
        return r;
    }

    @Before(Tx.class)
    public void applyRealName(String loginUid, String idType, String idNum, String idFront, String name, String idBack) {
        Kv cond = new Kv();
        cond.set("loginUid", loginUid);
        cond.set("idType", idType);
        cond.set("idNum", idNum);
        cond.set("idFront", idFront);
        cond.set("name", name);
        cond.set("idBack", idBack);
        cond.set("id", IdGen.uuid());
        Record r = isRealName(loginUid);
        if (null == r || "0".equals(r.get("state"))) {
            Db.update(Db.getSqlPara("shop.applyRealName", cond));
        }
    }

    @Before(Tx.class)
    public void feedback(String loginUid, List<String> imgs, String content) {
        String id = IdGen.uuid();
        Db.update(Db.getSqlPara("user.feedback", id, loginUid, content));
        for (String s : imgs
        ) {
            Db.update(Db.getSqlPara("user.feedbackImgs", IdGen.uuid(), id, s));
        }
    }

    public Page<Record> myNormalCoupon(String loginUid, int pageNumber) {
        Page<Record> list = Db.paginate(pageNumber, StaticPublic.PAGESIZE, Db.getSqlPara("shop.myNormalCoupon", loginUid));
        for (Record r : list.getList()
        ) {
            doImgPath(r);
        }
        return list;
    }

    public Page<Record> myProduct(String loginUid, int pageNumber) {
        Page<Record> page = Db.paginate(pageNumber, StaticPublic.LARGEPAGESIZE, Db.getSqlPara("mediaShop.myProduct", loginUid));
        for (Record r : page.getList()) {
            doImgPath(r);
            r.set("createDate", DateUtil.FormatDate(r.getDate("createDate")));
        }
        return page;
    }

    public Record myBox(String loginUid, int pageNumber) {
        Page<Record> list = Db.paginate(pageNumber, StaticPublic.PAGESIZE, Db.getSqlPara("shop.myNormalCoupon", loginUid));
        for (Record r : list.getList()
        ) {
            doImgPath(r);
        }
        Page<Record> page = Db.paginate(pageNumber, StaticPublic.LARGEPAGESIZE, Db.getSqlPara("mediaShop.myProduct", loginUid));
        for (Record r : page.getList()) {
            doImgPath(r);
            r.set("createDate", DateUtil.FormatDate(r.getDate("createDate")));
        }
        int totalPage = list.getTotalPage() > page.getTotalPage() ? list.getTotalPage() : page.getTotalPage();
        Record record = new Record();
        record.set("totalPage", totalPage);
        record.set("pageNumber", pageNumber);
        record.set("products", page.getList());
        record.set("coupons", list.getList());
        return record;
    }

    public Page<Record> myShelves(String loginUid, int pageNumber) {
        Page<Record> list = Db.paginate(pageNumber, StaticPublic.PAGESIZE, Db.getSqlPara("game.myShelves", loginUid));
        List<Record> list1 = Lists.newArrayList();
        if (null == list || list.getList().size() == 0) {

            for (int i = 1; i <= 3; i++) {
                list1.add(new Record().set("state", 0).set("rank", i));
            }
            return new Page<Record>(list1, pageNumber, StaticPublic.PAGESIZE, 1, 3);
        }

        Record r2;
        list1 = list.getList();
        for (Record r : list1
        ) {
            r.set("coupon", null);
            r.set("product", null);
            if (StrKit.notBlank(r.getStr("couponId"))) {
                r2 = Db.findFirst(Db.getSqlPara("game.getCouponByCouponId", r.getStr("couponId")));
                doShopPath(r2);
                r.set("coupon", r2);
            }
            if (StrKit.notBlank(r.getStr("productId"))) {
                r2 = Db.findFirst(Db.getSqlPara("game.getSaleProduct", r.getStr("productId")));
                doShopPath(r2);
                r.set("product", r2);
            }
        }
        if (list1.size() < 3) {
            int size = list.getList().size();
            int rank = list.getList().get(size - 1).getInt("rank");
            for (int i = 1; i <= 3 - size; i++
            ) {
                list1.add(new Record().set("state", 0).set("rank", rank + i));
            }
        }
        return new Page<Record>(list1, pageNumber, StaticPublic.PAGESIZE, list.getTotalPage(), list.getTotalRow());

        /*Page<Record> page=  Db.paginate(pageNumber,StaticPublic.LARGEPAGESIZE,Db.getSqlPara("mediaShop.mySaleProduct",loginUid));
        for (Record r:page.getList()){
            doImgPath(r);
            r.set("createDate",DateUtil.FormatDate(r.getDate("createDate")));
        }
        int totalPage =list.getTotalPage() >page.getTotalPage()?list.getTotalPage():page.getTotalPage();
        Record record=new Record();
        record.set("totalPage",totalPage);
        record.set("pageNumber",pageNumber);
        record.set("products",page.getList());
        record.set("coupons",list.getList());*/

    }

    @Before(Tx.class)
    public void productShelves(String loginUid, String productId, String state, int rank) {
        if ("1".equals(state)) {
            Record r1 = Db.findFirst(Db.getSqlPara("mediaShop.getShelvesByProduct", loginUid, productId));
            if (r1 != null) {
                throw new BusinessException("此商品已添加");
            }
            Db.update(Db.getSqlPara("mediaShop.productShelves", loginUid, productId));
            Record r = Db.findFirst(Db.getSqlPara("game.getShelvesByRank", loginUid, rank));
            if (null == r) {
                Db.update(Db.getSqlPara("game.saveShelvesByProduct", IdGen.uuid(), loginUid, rank, productId, DateUtil.addDate(30)));
            } else {
                Db.update(Db.getSqlPara("game.upShelvesByProduct", loginUid, rank, productId));
            }
        } else {
            Db.update(Db.getSqlPara("shop.downShelves", loginUid, rank));
            Db.update(Db.getSqlPara("mediaShop.productDownShelves", loginUid, productId));
        }
    }

    @Before(Tx.class)
    public void couponShelves(String loginUid, String couponId, String integral, String state, int rank) {
        if ("1".equals(state)) {
            //Db.update(Db.getSqlPara("shop.couponShelves", loginUid, couponId, integral));
            Record r = Db.findFirst(Db.getSqlPara("game.getShelvesByRank", loginUid, rank));
            if (null == r) {
                Db.update(Db.getSqlPara("game.saveShelvesByCoupon", IdGen.uuid(), loginUid, rank, couponId, DateUtil.addDate(30)));
            } else {
                Db.update(Db.getSqlPara("game.upShelvesByCoupon", loginUid, rank, couponId));
            }
            Db.update(Db.getSqlPara("shop.couponShelves", loginUid, couponId, integral));
        } else {
            Db.update(Db.getSqlPara("shop.downShelves", loginUid, rank));
            Db.update(Db.getSqlPara("shop.couponDownShelves", loginUid, couponId));
        }
    }

    @Before(Tx.class)
    public void buyShelves(String loginUid, int rank) {
        SqlPara sqlPara = Db.getSqlPara("user.selectUserIntegral", loginUid);
        Record record = Db.findFirst(sqlPara);
        int integral = record.getInt("integral");
        if (integral < 100) {
            throw new BusinessException("乐币不够");
        }
        // 减少乐币
        sqlPara = Db.getSqlPara("user.reduceIntegral", 100, loginUid);
        int i = Db.update(sqlPara);
        if (i == 0) {
            throw new BusinessException("乐币不够");
        }
        Db.update(Db.getSqlPara("game.saveShelves", IdGen.uuid(), loginUid, rank, DateUtil.addDate(30)));
    }


    public Page<Record> getShopShelves(String loginUid, int pageNumber, String snumber) {
        Page<Record> list = Db.paginate(pageNumber, StaticPublic.PAGESIZE, Db.getSqlPara("game.getShopShelves", snumber));
        List<Record> list1 = Lists.newArrayList();


        Record r2;
        list1 = list.getList();
        for (Record r : list1
        ) {
            r.set("coupon", null);
            r.set("product", null);
            if (StrKit.notBlank(r.getStr("couponId"))) {
                r2 = Db.findFirst(Db.getSqlPara("game.getCouponByCouponId", r.getStr("couponId")));
                doShopPath(r2);
                r.set("coupon", r2);
            }
            if (StrKit.notBlank(r.getStr("productId"))) {
                r2 = Db.findFirst(Db.getSqlPara("game.getSaleProduct", r.getStr("productId")));
                doShopPath(r2);
                r.set("product", r2);
            }
        }

        return new Page<Record>(list1, pageNumber, StaticPublic.PAGESIZE, list.getTotalPage(), list.getTotalRow());
    }

    public Page<Record> selectUserIntegral(String id, String type, int pageNumber) {
        Kv kv = Kv.create();
        kv.set("userId", id);
        if (type.equals("0")) {
            type = "";
        }
        kv.set("type", type);
        return Db.paginate(pageNumber, StaticPublic.LARGEPAGESIZE, Db.getSqlPara("user.selectUserIntegralList", kv));
    }

    @Before(Tx.class)
    public Record updateUserHeadImg(String portraitImg, String loginUid) {
        Db.update(Db.getSqlPara("user.updateUserHeadImg", portraitImg, loginUid));
        Record r = new Record();
        r.set("headImg", portraitImg);
        doImgPath(r);
        return r;
    }


    @Before(Tx.class)
    public void addRedPackLog(String loginUid, int money, String advId) {
        Db.update(Db.getSqlPara("user.addRedPackLog", IdGen.uuid(), loginUid, money, advId));
    }

    @Before(Tx.class)
    public void addRedPackLogEx(String loginUid, int money, String Id) {
        Db.update(Db.getSqlPara("user.addRedPackLogEx", IdGen.uuid(), loginUid, money, Id));
    }

    @Before(Tx.class)
    public void deleteVideo(String loginUid, String videoId) {
        Db.update(Db.getSqlPara("media.deleteAllAdvVideo", loginUid, videoId));
//        Db.update(Db.getSqlPara("media.deleteAdvDataVideo", loginUid, videoId));

    }
}
